package com.easycoding.ums.security.shiro.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import com.easycoding.framework.util.Tool;
import com.easycoding.ums.security.shiro.SessionKey;
import com.easycoding.ums.system.bo.UserTicket;
import com.easycoding.ums.system.entity.Permission;

public class PermissionsAuthorizationFilter extends AuthorizationFilter {
	

	public boolean isAccessAllowed(ServletRequest request,
			ServletResponse response, Object mappedValue) throws IOException {
		Subject subject = getSubject(request, response);
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		StringBuffer request_url = httpServletRequest.getRequestURL();
		String request_query = httpServletRequest.getQueryString();
		if (request_query != null) request_url.append("?" + request_query); 

		UserTicket user = (UserTicket)subject.getSession().getAttribute(SessionKey.USER);
		if(user != null){
			List<Permission> permissions  = user.getPermissions();
			if(permissions != null){
				for (Permission permission : permissions) {
					if(Tool.compareResource(permission.getEname(), request_url.toString()))
						return true;
				}
			}
		}
		

		return false;
	}

}
